/**
 * 
 */
package com.flashdeck.activity;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.ViewFlipper;

import com.flashdeck.Extras;
import com.flashdeck.R;
import com.flashdeck.dao.DeckDao;
import com.flashdeck.dao.impl.DeckDaoImpl;
import com.flashdeck.domain.Card;
import com.flashdeck.domain.Deck;
import com.flashdeck.domain.DeckProgress;

/**
 * @author Vincentas
 * 
 */
public class PlayDeckActivity extends Activity {

	
	private Deck deck;
	
	private Card currentCard;
	
	private DeckProgress deckProgress;
	
	private TextView frontTextView;
	
	private TextView backTextView;
	
	private ViewFlipper flipView;
	
	private Button correctButton;
	
	private Button incorrectButton;
	
	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onCreate(android.os.Bundle)
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.play_deck_layout);
		
		String deckId = getIntent().getExtras().getString(Extras.SELECTED_DECK);
		// TODO check if deckId is not null
		deck = getDeckDao().getDeck(deckId);
		// TODO check if deckInfo is not null
		deckProgress = getDeckDao().getDeckProgress(deckId);
				
		flipView = (ViewFlipper) findViewById(R.id.ViewFlipper01);		
		
		frontTextView = (TextView) findViewById(R.id.frontTextView);
		frontTextView.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				flipView.showNext();				
			}
		});
		
		backTextView = (TextView) findViewById(R.id.backTextView);
		
		correctButton = (Button) findViewById(R.id.correctButton);		
		correctButton.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				deckProgress.correctAnswer(currentCard);
				playNextCard();
			}
		});
		
		incorrectButton = (Button) findViewById(R.id.incorrectButton);
		incorrectButton.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				deckProgress.incorrectAnswer(currentCard);
				playNextCard();				
			}
		});
		
		currentCard = deck.getCard(deckProgress.getNextCardId());
		frontTextView.setText(currentCard.getFront());
		backTextView.setText(currentCard.getBack());
	}
	
	private void playNextCard() {
		currentCard = deck.getCard(deckProgress.getNextCardId());
		
		frontTextView.setText(currentCard.getFront());
		flipView.showNext();		
		backTextView.setText(currentCard.getBack());
	}
	
	public DeckDao getDeckDao() {
		return DeckDaoImpl.getInstance();
	}

	/* (non-Javadoc)
	 * @see android.app.Activity#onPause()
	 */
	@Override
	protected void onPause() {
		super.onPause();
		getDeckDao().saveDeckProgress(deckProgress);
	}
	
	
	
	
}
